import React, { useEffect, useRef, useState, useMemo, useContext } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect, history } from 'umi';
import { AssetListManageAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { assetListManageServices, deleteAssetManageService, exportAssetBudgetExportService, exportAssetService, removeAssetManageService } from '../services';
import { PrinterOutlined, DownloadOutlined, DeploymentUnitOutlined } from '@ant-design/icons';
import { AssetListManageContext } from '../mconfig/useManageContext';
import { message } from 'antd';
import { useDataSourceTable } from '../mconfig/useDataSourceTable';
import { fieldFlowExport, getKeyRouter, manageTableExpandIcon } from '@/utils';
import { ExportModal } from './AssetTypeModal';
import { PrintBarcode } from './PrintBarcode';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
// import '../../../../../public/js/honeywell_printer_sdk.js';
import { getBaseUrl } from '@/services/urlconst';

const AssetListTableManageView: React.FC<AssetListManageAPI.IMaterialManageView> = ({ curRes }) => {
  /**管理页services*/
  const { getAssetListTableData, assetListData, loading, pagination, searchList, manageTableParams, otherParams, loadMdicMapList } =
    assetListManageServices(curRes);

  /** 管理页的ref */
  const MaterialManageViewRef: any = useRef();

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /** 保存展示的表格数据 */
  const [dataSourceTable, setDataSourceTable] = useState<Record<string, any>[]>([]);

  /** 保存选中数据 */
  const [selectRowKeys, setSelectRowKeys] = useState<Record<string, any>>({ rowKeysList: [], valList: [] });

  /** 保存搜索参数 */
  const [searchParams, setSearchParams] = useState<any>({});

  /** 处理是否有子资产 */
  const { onExpandTable, childLoading } = useDataSourceTable(assetListData?.rows, dataSourceTable, setDataSourceTable, tableExpantKeys, setTableExpantKeys);

  /** 预算一体化导出弹窗 */
  const [openExportModal, setOpenExportModal] = useState<Record<string, any>>({
    openModal: false,
  });

  /** 打印条码弹窗 */
  const [openPrintBarcode, setOpenPrintBarcode] = useState<Record<string, any>>({
    openModal: false,
  });

  /** 移除提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
  });

  /** 移除弹框关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
    });
  };

  /** 切换头部方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    getAssetListTableData({ ...params, ...searchValues });
  };

  /** 导出回调 */
  const exportCallback = (res: any) => {
    /** 处理文件流 */
    fieldFlowExport(res, '资产信息数据.xlsx');
  };

  /** 预算一体化导出回调 */
  const exportAssetBudgetExportCallback = (res: any) => {
    /** 处理文件流 */
    fieldFlowExport(res, '预算一体化资产信息数据.xlsx');
  };

  /** 移除子资产回调 */
  const removeAssetManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadTableData();
    } else {
      message.error(res?.msg);
    }
  };

  /** 导出方法 */
  const { exportAssetRun, exportAssetLoading } = exportAssetService(curRes, exportCallback);
  const { exportAssetBudgetExportRun, exportAssetBudgetExportLoading } = exportAssetBudgetExportService(exportAssetBudgetExportCallback);

  /** 移除方法 */
  const { removeAssetManageRun, removeAssetManageLoading } = removeAssetManageService(removeAssetManageCallback);

  /** 删除组合资产方法回调 */
  const deleteAssetManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadTableData();
    } else {
      message.error(res?.msg);
    }
  };

  /** 删除组合资产方法 */
  const { deleteAssetManageRun, deleteAssetManageLoading } = deleteAssetManageService(deleteAssetManageCallback);

  /** 重置方法 */
  const onReset = (otherParams: AssetListManageAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 搜索方法 */
  const onSearch = (otherParams: AssetListManageAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 表格刷新数据 */
  const reloadTableData = () => {
    getAssetListTableData(manageTableParams);
    setSelectRowKeys({});
  };

  /** 分页方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getAssetListTableData({ pageSize, current, ...params });
  };

  /** Table操作列的事件池 */
  const operateFnc: AssetListManageAPI.IMaterialTableActionType = {
    /** 详情资产按钮 */
    onView: (record: Record<string, any>) => {
      history.push({
        pathname: `/assetInfo/resultant/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: record.id,
        },
      });
    },
    /** 编辑资产按钮 */
    onEdit: (record: Record<string, any>) => {
      /** 编辑资产按钮 */
      if (record.resultantAsset) {
        /** 编辑组合资产 */
        history.push({
          pathname: `/assetInfo/resultant/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'edit',
            id: record.id,
          },
        });
      } else {
        /** 编辑一级资产 */
        history.push({
          pathname: `/assetInfo/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'edit',
            id: record.id,
          },
        });
      }
      /** 移除子资产按钮 */
      // setOpenTipInfoModal({
      //   checkRowObj: record,
      //   showModal: true,
      // });
    },
    /** 删除资产按钮 */
    onCancel: (record: Record<string, any>) => {
      setOpenTipInfoModal({
        checkRowObj: record,
        showModal: true,
      });
    },
  };

  /** Table的columns集合 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, operateFnc);
  }, [curRes]);

  /** 设置多选框 */
  const oversightMemo = useMemo(() => {
    let rowSelectInfo: Record<string, any> = {};
    rowSelectInfo = {
      rowSelection: {
        type: 'checkBox',
        getCheckboxProps: (record: Record<string, any>) => ({
          // disabled: record.resultantAsset || record.pId,
          // disabled: record.pId,
        }),
        selectedRowKeys: selectRowKeys?.rowKeysList,
        onChange: (selectedRowKeys: React.Key[], selectedValList) => {
          setSelectRowKeys({
            rowKeysList: selectedRowKeys,
            valList: selectedValList,
          });
        },
      },
    };
    return rowSelectInfo;
  }, [selectRowKeys]);

  /** 管理页面头部操作集合 */
  const tableActionList: AssetListManageAPI.IHeaderActionType = useMemo(() => {
    return [
      {
        title: '组合',
        visible: curRes?.['/assetInfo/resultant'],
        type: 'primary',
        icon: <DeploymentUnitOutlined />,
        onClick: () => {
          history.push({
            pathname: `/assetInfo/resultant/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              selectRowKeys: [],
              returnPathName: history.location.pathname,
            },
          });
        },
      },
      {
        title: '资产导出',
        visible: curRes?.['/assetInfo/export'],
        type: 'primary',
        icon: <DownloadOutlined />,
        onClick: () => {
          if (dataSourceTable?.length > 0) {
            exportAssetRun(manageTableParams, otherParams);
          } else {
            message.warning('暂无资产导出！');
          }
        },
      },
      {
        title: '预算一体化导出',
        visible: curRes?.['/assetInfo/budgetExport'],
        type: 'primary',
        icon: <DownloadOutlined />,
        onClick: () => {
          setOpenExportModal({
            openModal: true,
          });
        },
      },
      {
        title: '打印条码',
        visible: true,
        type: 'primary',
        icon: <PrinterOutlined />,
        onClick: () => {
          if (selectRowKeys?.rowKeysList?.length > 0) {
            setOpenPrintBarcode({
              openModal: true,
            });
          } else {
            message.warning('请至少选择一个资产进行打印！');
          }
        },
        isRender: true,
      },
    ];
  }, [curRes, selectRowKeys, dataSourceTable, otherParams]);

  useEffect(() => {
    if (history.location.pathname == '/assetController/manage') {
      setSearchParams(manageTableParams);
      reloadTableData();
    }
  }, [history.location.pathname]);

  return (
    <>
      <div
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={tableActionList} // 操作按钮
          tableProps={{
            columns: columns,
            dataSource: dataSourceTable ? dataSourceTable : [],
            rowKey: 'id',
            loading: loading || childLoading || exportAssetBudgetExportLoading || exportAssetLoading || deleteAssetManageLoading,
            pagination: pagination as any,
            onPageChange: onPageChange,
            expandable: {
              // expandIcon: manageTableExpandIcon,
              onExpand: onExpandTable,
              expandedRowKeys: tableExpantKeys,
            },
            ...oversightMemo,
          }}
        />

        {/* 预算一体化导出弹框 */}
        {openExportModal?.openModal && (
          <ExportModal
            onClose={() => {
              setOpenExportModal({
                openModal: false,
              });
            }}
            modalTitle="预算一体化资产信息导出"
            searchParams={searchParams}
          />
        )}

        {/* 打印条码弹框 */}
        {openPrintBarcode?.openModal && (
          <PrintBarcode
            selectRowKeys={selectRowKeys}
            onClose={() => {
              setOpenPrintBarcode({
                openModal: false,
              });
            }}
            modalTitle="打印条码"
            searchParams={searchParams}
          />
        )}

        {/* 移除提示框 */}
        {openTipInfoModal?.showModal && (
          <TipsErrorModalNew
            // ref={tipErrorModalRef}
            modalLoading={removeAssetManageLoading}
            onClose={tipOnClose}
            modalOnOK={() => {
              deleteAssetManageRun(openTipInfoModal.checkRowObj.id);
            }}
            modalTip={'确认删除该资产，删除后不可恢复！'}
            tipTextColor="#000"
          />
        )}
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AssetListTableManageView);
